const router = require('koa-router')()
const request = require('request')

router.post('/generate', async (ctx, next) => {
  console.log(ctx.request.body.text);{
    generate(ctx.request.body.text)
  }
})



function generate(text){
  var requestInfo={
    method: "POST",
    url: "https://23329.o.apispace.com/aigc/txt2img",
    headers: {
       "X-APISpace-Token":"d724ba81cdae4c7489e9302d15ec7948",
       "Content-Type":"application/json"
    },
    body:`{\"task\":\"txt2img.sd\",\"params\":{\"model\":\"anime\",\"text\":\"${text}\",\"w\":512,\"h\":512,\"guidance_scale\":14,\"negative_prompt\":\"cropped, blurred, mutated, error, lowres, blurry, low quality, username, signature, watermark, text, nsfw, missing limb, fused hand, missing hand, extra limbs, malformed limbs, bad hands, extra fingers, fused fingers, missing fingers, bad breasts, deformed, mutilated, morbid, bad anatomy\",\"sampler\":\"k_euler\",\"seed\":1072366942,\"num_steps\":25},\"model\":\"anime\",\"text\":\"{{{ masterpiece }}}, exquisite facial features, masterpiece, perfect facial features, exquisite details, eyes, hair atmosphere, high resolution, 4K image quality, best light, delicate skin, detailed light, masterpiece, best quality,higher quality,high details, human head and deer body, sagittata, beautiful female face, long eyelashes, long silver hair, several braids, crystal bow and arrow, crystal translucent deer horn, corolla, silvery white fur wraps the whole body, no meat, crystal forest, magic, circle, masterpiece, masterpiece, ultra-high definition, countless golden light spots, dream charm, human personification, colorful light and shadow, top light, realistic effect, grade safety, unity, (ultra-fine CG:1.2),(8K:1.2), indoor, {{{{{wind blowing}}}}}}}}}} light, {{{}}}}}} {{{{{{{{{{{{{{{{{{{{{{{, 4k\",\"w\":512,\"h\":512,\"guidance_scale\":14,\"negative_prompt\":\"cropped, blurred, mutated, error, lowres, blurry, low quality, username, signature, watermark, text, nsfw, missing limb, fused hand, missing hand, extra limbs, malformed limbs, bad hands, extra fingers, fused fingers, missing fingers, bad breasts, deformed, mutilated, morbid, bad anatomy\",\"sampler\":\"k_euler\",\"seed\":1072366942,\"num_steps\":25,\"notify_url\":\"\"}`
 };
 request(requestInfo, function (error, response, body) {
     if (error) throw new Error(error);
     console.log(body);
     if(typeof(body) === 'string'){
      let res = JSON.parse(body)
      let pic = find(res.data.uid)
     }
     else{
      let pic = find(body.data.uid)
     }
 });  
}

function find(uid){
  var requestInfo={
    method: "POST",
    url: "https://23329.o.apispace.com/aigc/query-image",
    headers: {
       "X-APISpace-Token":"d724ba81cdae4c7489e9302d15ec7948",
       "Content-Type":""
    },
    body: `{\"uid\":\"${uid}\"}`
 };
 
 request(requestInfo, function (error, response, body) {
     if (error) throw new Error(error);
     console.log(body);
 });
}

module.exports = router